import { Injectable } from '@angular/core';
import { ApesMessageService } from '@shared/apes/message';
import { Subject, Subscription } from 'rxjs';
import { tap } from 'rxjs/operators';
import { AssemblyDrawingViewService } from '@core/services/assemblyDrawing/assemblyDrawing.view.service';
import { AssemblyDrawingApiService } from '@core/services/assemblyDrawing/assemblyDrawing.api.service';

interface BaseType {
  vin?: string;
  vehicleConfig?: string, // 配置车型编码
  brandName?: string,  // 汽车厂牌名称
  epcId?: string,  // epc编码
  epcVersion?: string,  // epc版本
  dataSource?: string, // 数据来源
  keyword?: string, // 关键词
  menuName?: string // 目录名

  QCCPMC?: string // 汽车厂牌名称
  PZCXID?: string // 车型编码
  selectorId?: string // 选择ID
  brandCode?: string // 汽车厂牌ID
  modelId?: string // 车型ID
}

@Injectable({
  providedIn: 'root',
})
export class AssemblyDrawingService {

  baseData: BaseType = {}; // 缓存当前查询的数据

  modelData: any = {};  // 缓存主表数据

  selectMenu$ = new Subject(); // 选择主组

  selectSubgroup$ = new Subject(); // 选择子组

  lastSubgroup$ = new Subject();

  nextSubgroup$ = new Subject();

  getQueryParam(...param) {
    return { ...this.baseData, ...param[0] };
  }

  getQueryMenuParam(...param) {
    return { ...this.baseData, 'MainGroup': param[0] };
  }

  constructor(
    private msgService: ApesMessageService,
    private assemblyDrawingApiService: AssemblyDrawingApiService,
    private assemblyDrawingViewService: AssemblyDrawingViewService,
  ) {
    // 选中主目录
    this.selectMenu$.subscribe(data => {

      // console.log('选中主目录',data);
      this.assemblyDrawingViewService.mainMenuChange$.next(data);
      this.baseData['mainGroupId'] = data['id'];
      if (data['selectorId'] && data['selectorId'] != '0') {
        this.baseData['mainSelectorId'] = data['selectorId'];
      } else {
        this.baseData['mainSelectorId'] = null;
      }

      this.assemblyDrawingApiService.querySubGroup(this.getQueryMenuParam(data))
        .pipe(
          tap((pipeSubData) => {
            // console.log('选中主目录解析子组数据中', pipeSubData);
            this.assemblyDrawingViewService.subgroupChange$.next({});
            this.assemblyDrawingViewService.clearSecondSurface();
          }),
        )
        .subscribe(subData => {
          // console.log('选中主目录解析子组数据结束', subData);
          this.assemblyDrawingViewService.subgroupChange$.next(subData);
        });

    });

    // 选中子目录
    this.selectSubgroup$.subscribe((data: any) => {
      // 如果当前为末级直接查询配件
      if (data['mainGroupCode']) {
        this.assemblyDrawingViewService.subMenuChange$.next(data);
        this.searchPartsList(data);
      } else {
        this.assemblyDrawingViewService.mainMenuChange$.next(data);
        this.baseData['mainGroupId'] = data['id'];
        if (data['selectorId'] && data['selectorId'] != '0') {
          this.baseData['mainSelectorId'] = data['selectorId'];
        } else {
          this.baseData['mainSelectorId'] = null;
        }
        this.assemblyDrawingApiService.querySubGroup(this.getQueryMenuParam(data))
          .pipe(
            tap((pipeSubData) => {
              // console.log('选中子目录解析子组数据中', pipeSubData);
              this.assemblyDrawingViewService.subgroupChange$.next({});
            }),
          )
          .subscribe(subData => {
            // console.log('选中子目录解析子组数据结束', subData);
            this.assemblyDrawingViewService.subgroupChange$.next(subData);
          });
      }
    });
  }

  //  开始解析
  startParse(param, model, publicPage) {
    this.baseData = param; // 缓存初始数据
    this.assemblyDrawingViewService.init(); // 初始化界面

    this.assemblyDrawingApiService.queryMotorcycleType(model)
      .subscribe((res) => {
          if (res) {
            this.assemblyDrawingViewService.showLoadingStep$.next({ step: 5, msg: '该车型停止服务，请提交钉钉审批‘开放车型服务申请’。' });
          } else {
            this.baseData['saleDept'] = model['saleDept'];
            this.assemblyDrawingApiService.queryCarConfig(this.getQueryParam())
              .pipe(
                tap((pipeConfigData) => {
                  // console.log('解析车型中', this.baseData, pipeConfigData);
                  this.baseData['QCCPMC'] = pipeConfigData['QCCPMC'];
                  this.baseData['QCCPID'] = pipeConfigData['QCCPID'];
                  this.baseData['PZCXID'] = pipeConfigData['PZCXID'];
                  pipeConfigData['publicPage'] = publicPage;
                  this.assemblyDrawingApiService.queryCarVIN(this.getQueryParam(pipeConfigData))
                    .pipe(
                      tap((pipeVINData) => {
                        // console.log('解析VIN中', pipeVINData);
                      }),
                    ).subscribe((VINData) => {
                    // console.log('解析VIN结束2', VINData);
                    this.analysisVIN(VINData);
                  });
                }),
              )
              .subscribe((configData) => {
                // console.log('解析车型结束2', configData);
                this.assemblyDrawingViewService.showLoadingStep$.next(2);
                this.assemblyDrawingViewService.modelInfoChange$.next(configData);
              });
          }
        },
      );

  }

  // 查询配件信息
  searchPartsList(data) {

    this.assemblyDrawingApiService.queryImgPoint(this.getQueryMenuParam(data)).pipe(
      tap((pipeImgData) => {
        // console.log('查询热点图中', pipeImgData);
      }),
    ).subscribe((ImgData) => {
      // console.log('查询热点图结束', ImgData);
      this.assemblyDrawingViewService.controlShowBtn$.next(false);
      this.assemblyDrawingViewService.showSecondSurface(ImgData);
      setTimeout(() => {
        if (data['sn']) {
          this.assemblyDrawingViewService.selectPartImg$.next(data['sn']);
        }
      }, 2000);
    });

    this.assemblyDrawingViewService.partsListLoadingChange$.next(true);
    this.assemblyDrawingApiService.queryParts(this.getQueryMenuParam(data)).pipe(
      tap((pipePartsData) => {
        // console.log('查询配件中', pipePartsData);
      }),
    ).subscribe((PartsData) => {
      // console.log('查询配件结束', PartsData);
      this.assemblyDrawingViewService.partsListLoadingChange$.next(false);
      this.assemblyDrawingViewService.partsListChange$.next(PartsData);
      setTimeout(() => {
        if (data['sn']) {
          this.assemblyDrawingViewService.selectPart$.next(data['sn']);
        }
      }, 2000);
    });
  }

  // 解析主组数据
  analysisVIN(data) {

    if (data['multiModel']) {
      this.assemblyDrawingViewService.carInfoChange$.next(data);
    } else if (data['selectorId']) {
      this.baseData['selectorId'] = data['selectorId'];
      this.baseData['brandCode'] = data['brandCode'];
      this.baseData['epcVersion'] = data['epcVersion'];
      this.assemblyDrawingApiService.queryMainGroup(this.getQueryParam(data))
        .pipe().subscribe((data) => {
        // console.log('解析主组数据结束2', data);
        this.assemblyDrawingViewService.menuChange$.next(data);
        this.assemblyDrawingViewService.subgroupChange$.next(data);
        this.assemblyDrawingViewService.showLoadingStep$.next(4);
        this.assemblyDrawingViewService.cacheDataChange$.next(this.baseData);
      });
      this.assemblyDrawingViewService.showLoadingStep$.next(3);
    } else {
      this.assemblyDrawingViewService.menuChange$.next([]);
      this.assemblyDrawingViewService.subgroupChange$.next([]);
      this.assemblyDrawingViewService.showLoadingStep$.next(5);
    }
    this.assemblyDrawingViewService.cacheDataChange$.next(this.baseData);
  }

  // 查询配件名信息
  searchParts(data) {
    this.assemblyDrawingViewService.showTypeChange$.next(3);
    this.assemblyDrawingViewService.controlShowBtn$.next(false);
    this.assemblyDrawingApiService.searchParts(this.getQueryParam(data)).pipe(
      tap((pipePartsData) => {
        // console.log('查询配件名中', pipePartsData);
      }),
    ).subscribe((PartsData) => {
      // console.log('查询配件名结束', PartsData);
      this.assemblyDrawingViewService.searchDataChange$.next(PartsData);
    });
  }

  // 查询匹配配件名信息
  searchMatchParts(data, type) {
    this.modelData = data['model'];
    let load = 0;
    this.assemblyDrawingViewService.showTypeChange$.next(3);
    this.assemblyDrawingViewService.controlShowBtn$.next(false);
    this.assemblyDrawingViewService.searchLoadingBtn$.next(true);
    let isStore = this.modelData.hasOwnProperty('belongDept'); // 所述部门
    //  no_auto:匹配车型 || yes:不匹配 || blurry:匹配车型(模糊搜索)
    if (type != 'blurry' && isStore) {

      // 车宝仓储(匹配配件)
      load = load + 1;
      this.assemblyDrawingViewService.searchMatchLoadingBtn$.next(true);
      this.assemblyDrawingApiService.searchMatchParts(this.getQueryParam(data)).pipe(
        tap((pipePartsData) => {
          // console.log('查询匹配配件名中', pipePartsData);
        }),
      ).subscribe((PartsData) => {
        // console.log('查询匹配配件名结束', PartsData);
        this.assemblyDrawingViewService.searchDataChange$.next(PartsData);
        this.assemblyDrawingViewService.searchMatchLoadingBtn$.next(false);
        load = load - 1;
        if (load == 0 || !PartsData) {
          this.assemblyDrawingViewService.searchLoadingBtn$.next(false);
        }
      });
      if (data.partsTag.hasOwnProperty('filterCondition') && data.partsTag.filterCondition.displayFilter) {
        // console.log('tag', data.partsTag);
        this.assemblyDrawingApiService.searchFilterCondition(data)
          .subscribe((FilterData) => {
            this.assemblyDrawingViewService.searchFilterDataChange$.next(FilterData);
          });
      }

      // 三头六臂
      load = load + 1;
      this.assemblyDrawingViewService.searchSanTouInquireLoadingBtn$.next(true);
      this.assemblyDrawingApiService.searchSanTouInquireParts(this.getQueryParam(data)).pipe(
        tap((pipePartsData) => {
          // console.log('查询三头六臂配件中', pipePartsData);
        }),
      ).subscribe((PartsData) => {
        // console.log('查询三头六臂配件结束', PartsData);
        this.assemblyDrawingViewService.searchSanTouInquireChange$.next(PartsData);
        this.assemblyDrawingViewService.searchSanTouInquireLoadingBtn$.next(false);
        this.assemblyDrawingApiService.searchSanTouInquirePrice(this.getQueryParam(data)).subscribe((PriceData) => {
          // console.log('查询三头六臂配件价格结束', PriceData);
          this.assemblyDrawingViewService.searchSanTouPriceChange$.next(PriceData);
        });
        load = load - 1;
        if (load == 0 || !PartsData) {
          this.assemblyDrawingViewService.searchLoadingBtn$.next(false);
        }
      });
    }
    if (type == 'no_auto' || type == 'blurry') {

      // 智能EPC(智能配件)
      load = load + 1;
      this.assemblyDrawingViewService.searchIntelligentLoadingBtn$.next(true);
      this.assemblyDrawingApiService.searchIntelligentParts(this.getQueryParam(data)).pipe(
        tap((pipePartsData) => {
          // console.log('查询智能配件名中', pipePartsData);
        }),
      ).subscribe((PartsData) => {
        // console.log('查询智能配件名结束', PartsData);
        this.assemblyDrawingViewService.searchDataChange$.next(PartsData);
        this.assemblyDrawingViewService.searchIntelligentLoadingBtn$.next(false);
        load = load - 1;
        if (load == 0 || !PartsData) {
          this.assemblyDrawingViewService.searchLoadingBtn$.next(false);
        }
      });
    }

    if (type == 'no_auto') {

      // 车宝商城(价格前置)
      load = load + 1;
      // let priceData = []
      this.assemblyDrawingViewService.searchPriceLoadingBtn$.next(true);
      this.assemblyDrawingApiService.searchPriceParts(this.getQueryParam(data)).pipe(
        tap((pipePriceData) => {
          // console.log('查询价格前置中', pipePriceData);
        }),
      ).subscribe((priceData) => {
        this.assemblyDrawingViewService.searchPriceLoadingBtn$.next(false);
        this.assemblyDrawingViewService.searchPriceChange$.next(priceData);
        load = load - 1;
        if (load == 0) {
          this.assemblyDrawingViewService.searchLoadingBtn$.next(false);
        }
      });
    }

    if (type == 'yes') {

      // 车宝商城(价格前置)
      load = load + 1;
      this.assemblyDrawingViewService.searchPriceLoadingBtn$.next(true);
      this.assemblyDrawingApiService.searchMismatchPriceParts(this.getQueryParam(data)).pipe(
        tap((pipePriceData) => {
          console.log('查询价格前置中', pipePriceData);
        }),
      ).subscribe((priceData) => {
        this.assemblyDrawingViewService.searchPriceLoadingBtn$.next(false);
        this.assemblyDrawingViewService.searchPriceChange$.next(priceData);
        load = load - 1;
        if (load == 0) {
          this.assemblyDrawingViewService.searchLoadingBtn$.next(false);
        }
      });
    }
  }

  // 查询分页匹配配件名信息
  searchMatchPart(data) {
    this.assemblyDrawingApiService.searchMatchParts(this.getQueryParam(data)).pipe(
      tap((pipePartsData) => {
      }),
    ).subscribe((PartsData) => {
      // console.log('查询分页匹配配件名结束', PartsData);
      this.assemblyDrawingViewService.searchDataChange$.next(PartsData);
      this.assemblyDrawingViewService.searchMatchLoadingBtn$.next(false);
      // this.assemblyDrawingViewService.searchPageDataChange$.next(PartsData);
    });
  }

  // 查询分页三头六臂配件名信息
  searchSanTouInquirePart(data) {
    this.assemblyDrawingApiService.searchSanTouInquireParts(this.getQueryParam(data)).pipe(
      tap((pipePartsData) => {
      }),
    ).subscribe((PartsData) => {
      console.log('查询分页三头六臂配件名结束', PartsData);
      this.assemblyDrawingApiService.searchSanTouInquirePrice(this.getQueryParam(data)).subscribe((PriceData) => {
        console.log('查询三头六臂配件价格结束', PriceData);
        this.assemblyDrawingViewService.searchSanTouPriceChange$.next(PriceData);
      });
      this.assemblyDrawingViewService.searchSanTouInquireChange$.next(PartsData);
      this.assemblyDrawingViewService.searchSanTouInquireLoadingBtn$.next(false);
    });
  }

  // 查询当前热点图信息
  searchImgPointParts(data, callBack) {
    let resData = {};
    this.assemblyDrawingApiService.queryImgPoint(this.getQueryMenuParam(data)).subscribe((ImgData) => {
      resData = ImgData;
      return callBack(resData);
    });
  }

  // 查询添加进购物车配件信息
  searchAddPartsList(data, callBack) {
    let load = 2;
    let resData = {};
    this.assemblyDrawingApiService.queryImgPoint(this.getQueryMenuParam(data)).subscribe((ImgData) => {
      load = load - 1;
      resData['ImgData'] = ImgData;
      this.assemblyDrawingViewService.imgSelectChange$.next(ImgData);
      if (load == 0) {
        return callBack(resData);
      }
    });
    this.assemblyDrawingApiService.queryParts(this.getQueryMenuParam(data)).subscribe((PartsData) => {
      load = load - 1;
      resData['PartsData'] = PartsData;
      if (load == 0) {
        return callBack(resData);
      }
    });
  }
}

